package com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisJDT

import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisZHT.AnalysisFragmentParentJdt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.AnalysisInforIndexHelp
import android.content.Context
import android.os.Handler
import android.text.Html
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.ShowDialogTools
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.RecyclerViewScrollHelper
import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.AudioPlayer
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragment
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.PaperPerAnalysisInfor
import com.lancoo.znbkxx.teacher.utils.LancooAnim
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils.setWebImageClick
import com.lancoo.znbkxx.teacher.widget.KWebView
import kotlinx.android.synthetic.main.aibk_adapter_parent_jdt.view.*
import kotlinx.android.synthetic.main.aibk_include_article_view.view.*
import kotlinx.android.synthetic.main.aibk_include_child_answer_title_infor.view.*
import kotlinx.android.synthetic.main.aibk_include_parent_audioplayer_a.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_answer_view.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_assessment.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_web_ask_view.view.*
import kotlinx.android.synthetic.main.aibk_include_question_information_view.view.*
import kotlinx.android.synthetic.main.aibk_fragment_model_splitlayout.view.*
import java.text.SimpleDateFormat
import java.util.*

class AnalysisFragmentJdt(
        val activity:AppCompatActivity,
        val paperPerAnalysisInfor: PaperPerAnalysisInfor,
        val index_A:Int,
        val index_B:Int
) : KBaseFragment(), View.OnClickListener {

    private var rootView: View? = null
    private var childVpPosition = 0
    private var scorllPosition = 0
    private var isAddView = false
    private var fragmentList: MutableList<Fragment>? = ArrayList()

    override fun createLayout(): Int {
        return R.layout.aibk_fragment_model_splitlayout
    }

    override fun initView(view: View?) {
        rootView = view
        rootView!!.RlArticleView.visibility = View.GONE
        rootView!!.RlAudioPlayer.visibility = View.GONE
        rootView!!.IvPlayOrPause.setOnClickListener(this)
        rootView!!.IBtnArticle.setOnClickListener(this)

        showQuestionView()
    }

    //显示试题内容
    private fun showQuestionView() {

        //是否显示来源
        var resource = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].Resource
        if (resource.isEmpty()) {
            rootView!!.IncludeQuesInformationView.visibility = View.GONE
        } else {
            rootView!!.IncludeQuesInformationView.visibility = View.VISIBLE
            rootView!!.IncludeQuesInformationView.TvSourceFrom.text = "来源: $resource"
            //隐藏试题准确率
            rootView!!.IncludeQuesInformationView.TvScoreRate.visibility = View.GONE
        }

        //隐藏单题评估系数
        rootView!!.RlQuesAssessment.visibility = View.GONE

        //加载题干内容
        var quesBody = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].QuesBody
        val childAsk = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ChildList[0].ChildAsk
        val childAnswerType = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ChildList[0].ChildAnswerType
        var ask = ""
        val typeNo = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].TypeNo
        if (typeNo == "Q") {//阅读填空
            var childListSize = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ChildList.size
            if(childListSize == 1){
                ask = "$quesBody<br>$childAsk"
            }else{
                ask = childAsk
            }
        } else if (typeNo == "X" || typeNo == "G") {//X:阅读简单 G:听力简答
            if (typeNo == "G") {//G:听力简答
                var timeLength = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].QuesAudio.TimeLength
                val format = SimpleDateFormat("mm:ss", Locale.CHINA)
                rootView!!.TvAudioTotalTime.text = format.format(timeLength*1000)
                rootView!!.RlAudioPlayer.visibility = View.VISIBLE
                var article = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].QuesAudio.Article
                article = "听力原文：<br>$article"
                if (WebStyleUtils.hasTable(article)) {
                    WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvArticle, article, false)
                } else {
                    WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvArticle, article, true)
                }

                rootView!!.IBtnArticle.visibility = View.VISIBLE
                rootView!!.RlArticleView.visibility = View.GONE
                Handler().postDelayed({
                    rootView!!.IBtnArticle.performClick()
                }, 300)

            }else{
                ask = quesBody
            }
        } else if (typeNo == "k") {//阅读综合
            if (childAnswerType == 32) {//匹配题综合
                ask = quesBody + childAsk
            } else {
                ask = quesBody
            }
        } else if (typeNo == "b" || typeNo == "V" || typeNo == "d") {//b:补全对话 V:连词成句 d:看图写句子
            if(quesBody.isEmpty()){
                ask = childAsk
            }else{
                ask = quesBody
            }
        } else if (typeNo == "g") {//翻译题
            if(quesBody.isEmpty()){
                ask = childAsk
            }else{
                ask = quesBody
            }
        }

        if (WebStyleUtils.hasTable(ask)) {
            WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvAsk, ask, false)
        } else {
            WebStyleUtils.showWebViewCssStyle(activity, rootView!!.WvAsk, ask, true)
        }
        rootView!!.WvAsk.addJavascriptInterface(
                JSInterface(
                        activity,
                        WebStyleUtils.returnImageUrlsFromHtml(ask)
                ), "Android"
        )

        rootView!!.WvAsk.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                rootView!!.RlWebLoading.visibility = View.GONE
                setWebImageClick(view, "Android")

                isAddView = true
                handler.sendEmptyMessageDelayed(0, 100)
            }
        }

        rootView!!.WvAsk.setOnScrollChangeListener(object : KWebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达地端")
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达顶端")
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "=======oldt========$oldt")
            }
        })

        //加载作答区域
        fragmentList!!.clear()

        var childListSize = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ChildList.size
        for (c in 0 until childListSize) {
            (fragmentList as ArrayList<Fragment>).add(
                    AnalysisFragmentParentJdt(activity,paperPerAnalysisInfor, index_A,index_B, c)
            )
        }

        val mAdapter = KBaseFragmentPagerAdapter(childFragmentManager, fragmentList as ArrayList<Fragment>)
        rootView!!.VpAnswer.adapter = mAdapter
        rootView!!.VpAnswer.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                childVpPosition = position
                showChildVpInfor()
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    private fun showChildVpInfor() {
        val childListSize = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].ChildList.size
        if(childListSize == 1){
            rootView!!.TvChildAnswerCurrent.visibility = View.GONE
        }else{
            rootView!!.TvChildAnswerCurrent.visibility = View.VISIBLE
        }
        val quesChildNum = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].QuesChildNum
        rootView!!.TvChildAnswerCount.text = Html.fromHtml(resources.getString(R.string.aibk_jdt_child_count, quesChildNum))
        rootView!!.TvChildAnswerCurrent.text = Html.fromHtml(resources.getString(R.string.aibk_current_child_vp, childVpPosition + 1, quesChildNum))
    }

    //JS点击事件处理
    inner class JSInterface(var context: Context, var imageUrls: Array<String>?) {

        @JavascriptInterface
        fun clickFunction(position: String) {
            return
        }

        //java回调js代码，不要忘了@JavascriptInterface这个注解，不然点击事件不起作用
        @JavascriptInterface
        fun openImage(img: String, pos: Int) {
            val paths = ArrayList<String>()
            paths.add(img)
            Log.e("openImage", "$pos========点击了图片=========$img")
            ShowDialogTools.showBigImageDialog(activity, img)
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.IvPlayOrPause -> {
                var quesAudioPath = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].QuesAudio.Path
                audioPlayer = AudioPlayer(
                        activity, rootView!!.IvPlayOrPause,
                        rootView!!.SeekBarProgress,
                        rootView!!.TvAudioCurrentTime,
                        rootView!!.TvAudioTotalTime,
                        quesAudioPath,
                        AudioPlayer.ParentAudioListener {
                            val audioSpeed = paperPerAnalysisInfor.TypeList[index_A].QuesDetailList[index_B].AudioSpeed
                            audioPlayer!!.setPlaySpeed(audioSpeed.toFloat())
                        })
            }
            R.id.IBtnArticle ->{
                if (rootView!!.RlArticleView.visibility == View.GONE) {
                    rootView!!.IBtnArticle.setImageResource(R.mipmap.aibk_audioplayer_article_close)
                    LancooAnim.expand(rootView!!.RlArticleView)
                } else {
                    rootView!!.IBtnArticle.setImageResource(R.mipmap.aibk_audioplayer_article_open)
                    LancooAnim.collapse(rootView!!.RlArticleView)
                }
            }
        }
    }

    //答题卡跳转
    fun fragmentJumpToSortIndex(itemSortIndex: String) {
        scorllPosition = AnalysisInforIndexHelp.ItemSortIndex_return_IndexD(paperPerAnalysisInfor, itemSortIndex)
        childVpPosition = AnalysisInforIndexHelp.ItemSortIndex_return_IndexC(paperPerAnalysisInfor, itemSortIndex)
        handler.sendEmptyMessageDelayed(0, 100)
    }
    //答题卡跳转辅助方法
    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0 -> {
                rootView!!.VpAnswer.setCurrentItem(childVpPosition, true)
                showChildVpInfor()
                //实现滚动并定位在顶部
                val fragment = fragmentList!![childVpPosition] as AnalysisFragmentParentJdt
                RecyclerViewScrollHelper.scrollToPosition(fragment.rootView!!.RvShotAnswer, scorllPosition)

            }
        }
        false
    })
}